package com.rabbitmq.confirm.addConfirmListener;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmListener;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.utils.RabbitMQUtils;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Send {
    public static void main(String[] args) {
        //创建工厂对象用于指定链接的信息
        //创建链接以及通道,并添加异常处理同时在try..catch执行完成后自动释放资源
        try {
            final Connection connection = RabbitMQUtils.getConnection();
            final Channel channel = connection.createChannel();
            String queueName = "confirmQueue";
            channel.queueDeclare(queueName, true, false, false, null);
            String exchangeName = "directExchange";
            channel.exchangeDeclare(exchangeName, "direct", true);
            channel.queueBind(queueName, exchangeName, "confirmKey");

            String message = "发送者确认模式的测试消息";
            //开启开启发送者确认模式
            channel.confirmSelect();

            /**
             * 异步监听确认:addConfirmListener底层会启动子线程来监听队列
             */
            channel.addConfirmListener(new ConfirmListener() {
                //消息成功接收后的回调 参数 1 为消息编号  参数 2 为是否批量
                public void handleAck(long l, boolean b) throws IOException {
                    System.out.println(String.format("消息接收成功:\n\t消息编号:%s\n\t消息是否批量确认:%s", l, b));
                }

                //消息接收失败后的回调 参数 1 为消息编号  参数 2 为是否批量
                public void handleNack(long l, boolean b) throws IOException {
                    System.out.println(String.format("消息接收失败:\n\t消息编号:%s\n\t消息是否批量确认:%s", l, b));
                }
            });

            for (int i = 0; i < 20; i++) {
                channel.basicPublish(exchangeName, "confirmKey", null, message.getBytes());
            }

            System.out.println("消息发送成功");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {

        }
    }
}
